import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'

// 请求拦截器
http.intercept.request = (config) => {
  const token = getApp().token
  if (token && !config.url.includes('/refreshToken')) {
    config.header = config.header || {}
    config.header.Authorization = token
  }
  return config
}

// 配置响应拦截器
http.intercept.response = async (res) => {
  console.log(res);
  // 判断接口返回的代码，如果是401，代表token失效
  if (res.statusCode === 401) {
    // 如果刷新token接口返回401，代表refreshtoken失效
    if (res.config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const currentPage = pageStack[pageStack.length - 1]
      wx.redirectTo({
        url: `/pages/login/index?returnUrl=/${currentPage.route}`
      })
      return res.data
    }
    const { code, data } = await wx.http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: getApp().refreshToken
      }
    })
    if (code !== 10000) return wx.utils.toast()
    console.log(data);
    // 更新token和 refreshToken
    getApp().setToken(data.token, data.refreshToken)

    const result = await wx.http({
      ...res.config
    })
    return result
  }
  // 过滤接口返回的数据
  return res.data
}
// 挂载到wx全局对象
wx.http = http

export default http